<?php
require_once("../core/core.inc");

function action($cmd, $msg, $params, $vars = false) {
	$r = "<div style='border:solid 1px silver'>".$msg."<br><form method='post' action='backend.php'>";
	if($vars!==false) {
		foreach($vars as $k => $v) {
			$r .= "<input type='hidden' name='$k' value='$v'>\n";
		}
	}
	$r .= "<input type='hidden' name='cmd' value='$cmd'>";
	foreach($params as $k => $v){
		$r .= "$v <input type='text' name='$k'/>";
	}
	$r .= "<input type='submit' name='ok' value='Do'></form></div>";
	echo $r;
}

function lnk($cmd, $msg, $params) {
	echo "<a href='backend.php?cmd=".$cmd;
	foreach($params as $k => $v) {
		echo "&".$k."=".$v;
	}
	echo "'>".$msg."</a>";
}

function dbg($v){
	echo "<pre>";
	print_r($v);
	echo "</pre>";
}

// TODO: check if it's real backend

$p = Utils::params();

switch(Utils::get("cmd", false)) {
	case "createuser":
		if($backend) {
			$usr = new User();
			$usr->name = $p["name"];
			echo "User created:".DB::save($usr);
		}
		break;
	case "addPlayer":
			$gm = DB::load($p["game"]);
			$gm->registerPlayer($p["player"]);
			DB::save($gm);
			dbg($gm);
			break;
	case "createserver":
		$s = new Server();
		$s->name = $p["name"];
		DB::save($s);
		echo "Server created:".$s->id;
	case "gamereset":
		$game = DB::load($p["id"]);
		$game->reset();
		DB::save($game);
		dbg($game);
		break;
	case "playerlist":
		echo "Players:";
		$usrs = Users::lst();
		foreach($usrs as $k => $v) {
			echo "<li>".$k.":".$v;
		}
		break;
	case "gamelist":
		$games = Server::_()->gameList();
		echo "Games:<br><table border=1>";
		foreach($games as $k => $v) {
			echo "<tr><td valign=top>".$k."</td><td><pre>";
			print_r($v);
			echo "</pre></td><td valign=top>";
			lnk("gamereset", "Reset", array("id" => $k));
			action("addPlayer", "Add player", array("player" => "Player id"), array("game" => $k));
			echo "</td></tr>";
		}
		echo "</table>";
		break;
	case "addtttgame":
		$s = Server::_();
		$s->addGames(1, "TicTacToe");
		DB::save($s);
		dbg($s);
		break;
	case false:
		break;
}

action("createuser", "Create new user", array("name" => "User name", "pw"=> "User password"));
echo "<li>";
lnk("gamelist", "Games list", array());
echo "<li>";
lnk("playerlist", "Players list", array());
echo "<li>";
lnk("addtttgame", "Add TTT game", array());

?>



